import { Upload, Button, message, Space, Typography, Card, UploadProps } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import React from 'react';
import axios from 'axios';
import { uploadFailNotification, uploadSuccessNotification, uploadWarningNotification } from '../ant-form/antForm.notification';
import { getRequestUrl } from '../ant-form/antForm.const';

const { Title } = Typography;

interface AntUploadState {
  fileList: any;
  uploading: boolean
}

interface AntUploadProps {
}

export class AntUpload extends React.Component<AntUploadProps, AntUploadState> {
  constructor(props: AntUploadProps) {
    super(props);
    this.state = {
      fileList: [],
      uploading: false,
    }
  }

  handleUpload = () => {
    const { fileList } = this.state;
    const formData = new FormData();
    fileList.forEach((file: any) => {
      formData.append('files[]', file);
    });
    this.setState({
      uploading: true,
    });

    axios.post(getRequestUrl() + "/action/uploadFirmware", formData, {
      headers: {
        'Content-Type': 'multipart/form-data;',
        "Accept": "*/*"
      }
    })
      .then(res => {
        const { status } = res;
        if (status == 200) {
          uploadSuccessNotification();
        } else if (status == 206) {
          uploadWarningNotification();
        }

      })
      .then(() => {
        this.setState({
          fileList: [],
        });
      })
      .catch((e) => {
        uploadFailNotification();
      })
      .finally(() => {
        this.setState({
          uploading: false,
        });
      });
  };

  render() {
    const { uploading, fileList } = this.state;
    const props: UploadProps = {
      onRemove: (file: any) => {
        this.setState({
          fileList: [],
        });
      },
      beforeUpload: (file: any) => {
        this.setState(state => ({
          fileList: [file],
        }));
        return false;
      },
      fileList,
    };

    return (
      <Space direction={"vertical"}>
        <Card>
          <Title level={2}>固件上传</Title>
          <Upload  {...props}>
            <Button icon={<UploadOutlined />}>请选择固件文件</Button>
          </Upload>
          <Button
            type="primary"
            onClick={this.handleUpload}
            disabled={fileList.length === 0}
            loading={uploading}
            style={{ marginTop: 16 }}
          >
            {uploading ? '上传中' : '开始上传'}
          </Button>
        </Card>
      </Space>
    );
  }
}
